package com.smart4j.framework;

import com.smart4j.framework.bean.Data;
import com.smart4j.framework.bean.Handler;
import com.smart4j.framework.bean.Param;
import com.smart4j.framework.bean.View;
import com.smart4j.framework.helper.BeanHelper;
import com.smart4j.framework.helper.ConfigHepler;
import com.smart4j.framework.helper.ControllerHelper;
import com.smart4j.framework.util.CodeUtil;
import com.smart4j.framework.util.JsonUtil;
import com.smart4j.framework.util.ReflectionUtil;
import com.smart4j.framework.util.StreamUtil;

import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 请求转发器
 *
 * @author 段誉
 * @create 2019-04-01 17:27
 */
@WebServlet(urlPatterns = "/*", loadOnStartup = 0)
public class DispatcherServlet extends HttpServlet {
  /**
   * 初始化
   */
  @Override
  public void init(ServletConfig config) throws ServletException {
    //初始化相关Helper类
    HelperLoad.init();
    //获取ServletContext对象（用于注册Servlet）
    ServletContext servletContext = config.getServletContext();
    //注册处理JSP的Servlet
    ServletRegistration jspServlet = servletContext.getServletRegistration("jsp");
    jspServlet.addMapping(ConfigHepler.getAppJspPath() + "*");
    //注册处理静态资源的默认Servlet
    ServletRegistration defaultServlet = servletContext.getServletRegistration("default");
    defaultServlet.addMapping(ConfigHepler.getAppAssetPath() + "*");
  }

  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    //获取请求方法与路径，全
    String requestMethod = req.getMethod().toLowerCase();
    String requestPath = req.getPathInfo();
    //获取Action处理器
    Handler handler = ControllerHelper.getHandler(requestMethod, requestPath);
    //如果没有找到则结束运行
    if (handler == null) {
      return;
    }
    //获取controller类及其bean实例
    Class<?> controllerClass = handler.getControllerClass();
    Object controllerBean = BeanHelper.getBean(controllerClass);
    //创建请求参数对象
    Map<String, Object> paramMap = new HashMap<>();
    Enumeration<String> parameNames = req.getParameterNames();
    while (parameNames.hasMoreElements()) {
      String paramName = parameNames.nextElement();
      String paramValue = req.getParameter(paramName);
      paramMap.put(paramName, paramValue);
    }
    String body = CodeUtil.decodeURL(StreamUtil.getString(req.getInputStream()));
    if (StringUtils.isNoneEmpty(body)) {
      String[] params = StringUtils.split(body, "&");
      if (ArrayUtils.isNotEmpty(params)) {
        for (String param : params) {
          String[] array = StringUtils.split(param, "=");
          if (ArrayUtils.isEmpty(array) || array.length != 2) {
            String paramName = array[0];
            String paramValue = array[1];
            paramMap.put(paramName, paramValue);
          }
        }
      }
    }
    Param param = new Param(paramMap);
    //调用action方法
    Method actionMethod = handler.getActionMethod();
    Object result;
    //判断如果没有参数则不传递
    if (actionMethod.getParameterCount() > 0) {
      result = ReflectionUtil.invokeMethod(controllerBean, actionMethod, param);
    } else {
      result = ReflectionUtil.invokeMethod(controllerBean, actionMethod);
    }
    //处理action方法返回值
    if (result instanceof View) {
      //返回jsp页面
      View view = (View) result;
      String path = view.getPath();
      if (path.startsWith("/")) {
        resp.sendRedirect(requestPath + path);
      } else {
        Map<String, Object> model = view.getModel();
        for (Map.Entry<String, Object> entry : model.entrySet()) {
          req.setAttribute(entry.getKey(), entry.getValue());
        }
        req.getRequestDispatcher(ConfigHepler.getAppJspPath() + path).forward(req, resp);
      }
    } else if (result instanceof Data) {
      //返回JSON数据
      Data data = (Data) result;
      Object model = data.getModel();
      if (model != null) {
        resp.setContentType("application/json");
        resp.setCharacterEncoding("UTF-8");
        PrintWriter writer = resp.getWriter();
        String json = JsonUtil.toJson(model);
        writer.write(json);
        writer.flush();
        writer.close();
      }
    }
  }
}
